#include "scan_check.h"
#include "qrencode.h"
#include "qdebug.h"

Scan_Check::Scan_Check(QString uuid, Http_Get* parent) :
    Http_Get(parent)
{
    m_uuid = uuid;
    m_tip = "1";

    qDebug() << "QRcode path:" << "https://login.weixin.qq.com/qrcode/" + m_uuid + "?t=webwx";
    qDebug() << "QRcode:" << LOGIN_QRCODE_PREFIX + m_uuid;

    printf_qrcode(LOGIN_QRCODE_PREFIX + m_uuid);

    scan_timer = new QTimer;
    connect(scan_timer, SIGNAL(timeout()), this, SLOT(timer_to_scan()));

    timer_to_scan();
}

Scan_Check::~Scan_Check()
{

}

void Scan_Check::printf_qrcode(const QString qrcode)
{
    QRcode *qrcode_obj;

    qrcode_obj = QRcode_encodeString(qrcode.toStdString().c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);

    printf("ver:%d width:%d\n", qrcode_obj->version, qrcode_obj->width);

    uint8_t *pdata = qrcode_obj->data;
    for(int i = 0; i < qrcode_obj->width; ++i) {
        for(int j = 0; j < qrcode_obj->width; ++j) {
            if(*pdata & 0x01)
                printf("\e[0;40m  \033[0m");
            else
                printf("\e[1;47m  \033[0m");

            ++pdata;
        }
        printf("\n");
    }

    QRcode_free(qrcode_obj);
}

void Scan_Check::timer_to_scan()
{
    get(m_uuid, m_tip);
}

void Scan_Check::get(QString &uuid, QString tip)
{
    QString url = LOGIN_SERVER_HOST + WX_CGI_PATH + "login?uuid=" + uuid +
        "&tip=" + tip + "&_=" + QString::number(time(NULL));

#if QWX_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << url;
#endif

    Http_Get::get(url);
}

void Scan_Check::finished(QNetworkReply* reply)
{
    QString replyStr(reply->readAll());
    QString qrredirect_uriStr = "window.redirect_uri=\"";
    QString redirect_uriStr = "";
    int index = -1;

#if QWX_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
    qDebug() << "context:" << replyStr;
#endif

    if (replyStr == "window.code=408;") {
        timer_to_scan();
        return;
    }
    else if (replyStr == "window.code=201;") {
        Q_EMIT scanedButWaitConfirm();

        m_tip = "0";
        //scan_timer->start(2000);
        timer_to_scan();
        return;
    }
    else if (replyStr.contains("window.code=200;")) {
        scan_timer->stop();

        index = replyStr.indexOf(qrredirect_uriStr);
        if (index == -1) {

            qWarning() << "ERROR:" << __PRETTY_FUNCTION__ <<
                "redirect_uri not found!";

            Q_EMIT scanedAndConfirmed(redirect_uriStr);
            return;
        }

        index += qrredirect_uriStr.size();
        redirect_uriStr = replyStr.mid(index, replyStr.size() - index - 2);

#if QWX_DEBUG
        qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << redirect_uriStr;
#endif

        Q_EMIT scanedAndConfirmed(redirect_uriStr);
        return;
    }
    else {
        Q_EMIT error();
    }
}
